<?php

function cleanit($text) {
    return htmlentities(strip_tags(stripslashes($text)), ENT_COMPAT, "UTF-8");
}

function escape($data) {
    return cleanit($data);
}

function insert_get_username_from_userid($var) {
    global $conn;
    $query = "SELECT username FROM members WHERE USERID='" . mysql_real_escape_string($var[USERID]) . "'";
    $executequery = $conn->execute($query);
    $getusername = $executequery->fields[username];
    echo "$getusername";
}

function insert_assign_username_from_userid($var) {
    global $conn;
    $query = "SELECT username FROM members WHERE USERID='" . mysql_real_escape_string($var[USERID]) . "'";
    $executequery = $conn->execute($query);
    $getusername = $executequery->fields[username];
    return "$getusername";
}

function insert_get_advertisement($var) {
    global $conn;
    $query = "SELECT code FROM advertisements WHERE AID='" . mysql_real_escape_string($var[AID]) . "' AND active='1' limit 1";
    $executequery = $conn->execute($query);
    $getad = $executequery->fields[code];

    if (get_magic_quotes_gpc())
        echo stripcslashes($getad);
    else
        echo $getad;
}

function verify_login_admin() {
    global $config, $conn;
    if ($_SESSION['ADMINID'] != "" && is_numeric($_SESSION['ADMINID']) && $_SESSION['ADMINUSERNAME'] != "" && $_SESSION['ADMINPASSWORD'] != "") {
        $query = "SELECT * FROM administrators WHERE username='" . mysql_real_escape_string($_SESSION['ADMINUSERNAME']) . "' AND password='" . mysql_real_escape_string($_SESSION['ADMINPASSWORD']) . "' AND ADMINID='" . mysql_real_escape_string($_SESSION['ADMINID']) . "'";
        $executequery = $conn->execute($query);

        if (mysql_affected_rows() == 1) {
            
        } else {
            header("location:$config[adminurl]/index.php");
            exit;
        }
    } else {
        header("location:$config[adminurl]/index.php");
        exit;
    }
}

function insert_get_runtime($var) {
    $tempruntime = $var[runtime];
    $mins = floor($tempruntime / 60);
    $secs = round(($tempruntime - ($mins * 60)), 0);
    echo "{$mins} min {$secs} sec";
}

function insert_get_profile_comment_added_time($a) {
    global $conn;
    $query = "SELECT time_added FROM members_comments WHERE CID='" . mysql_real_escape_string($a[cid]) . "'";
    $executequery = $conn->execute($query);
    $timeadded = $executequery->fields[time_added];
    echo date('Y-m-d', $timeadded);
}

function seo_clean_titles($title) {
    $title = str_replace(array('&Agrave;', '&agrave;', '&Aacute;', '&aacute;', '&Egrave;', '&egrave;', '&Eacute;', '&eacute;', '&Igrave;', '&igrave;', '&Iacute;', '&iacute;', '&Ntilde;', '&ntilde;', '&Ograve;', '&ograve;', '&Oacute;', '&oacute;', '&Ugrave;', '&ugrave;', '&Uacute;', '&uacute;', '&Uuml;', '&uuml;', '&Atilde;', '&sup3;', '&aelig;', '&thorn;', '&aacute;', '&eth;', '&uml;', '&ouml;', '&Ouml;'), array('A', 'a', 'A', 'a', 'E', 'e', 'E', 'e', 'I', 'i', 'I', 'i', 'N', 'n', 'O', 'o', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'o', '', 'ae', 'th', 'a', 'd', 'o', 'o', 'O'), $title);
    $title = str_replace("&amp;", "&", $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $title = str_replace(
            array(":", "?", ".", "!", "$", "^", "*", ",", ";", "'", '"', "%", "~", "@", "#", "[", "]", "<", ">", "\\", "/", "=", "+"), "", $title);
    $title = str_replace(array('_', " ", "&"), array("-", "-", "und"), $title);
    $title = htmlentities(strtolower($title));
    $title = str_replace(array('&auml;', '&ouml;', '&uuml;', '&szlig;'), array('ae', 'oe', 'ue', 'ss'), $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $results = rawurlencode($title);

    global $config, $conn;
    $query = "SELECT value FROM config WHERE setting='seo_title_include'";
    $executequery = $conn->execute($query);
    $seo_title_include = $executequery->fields[value];

    echo $results . $seo_title_include;
}

function seo_clean_titles_no_trail($title) {
    $title = str_replace(array('&Agrave;', '&agrave;', '&Aacute;', '&aacute;', '&Egrave;', '&egrave;', '&Eacute;', '&eacute;', '&Igrave;', '&igrave;', '&Iacute;', '&iacute;', '&Ntilde;', '&ntilde;', '&Ograve;', '&ograve;', '&Oacute;', '&oacute;', '&Ugrave;', '&ugrave;', '&Uacute;', '&uacute;', '&Uuml;', '&uuml;', '&Atilde;', '&sup3;', '&aelig;', '&thorn;', '&aacute;', '&eth;', '&uml;', '&ouml;', '&Ouml;'), array('A', 'a', 'A', 'a', 'E', 'e', 'E', 'e', 'I', 'i', 'I', 'i', 'N', 'n', 'O', 'o', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'o', '', 'ae', 'th', 'a', 'd', 'o', 'o', 'O'), $title);
    $title = str_replace("&amp;", "&", $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $title = str_replace(
            array(":", "?", ".", "!", "$", "^", "*", ",", ";", "'", '"', "%", "~", "@", "#", "[", "]", "<", ">", "\\", "/", "=", "+"), "", $title);
    $title = str_replace(array('_', " ", "&"), array("-", "-", "und"), $title);
    $title = htmlentities(strtolower($title));
    $title = str_replace(array('&auml;', '&ouml;', '&uuml;', '&szlig;'), array('ae', 'oe', 'ue', 'ss'), $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $results = rawurlencode($title);
    echo "$results";
}

function seo_clean_titles_sendmail($title) {
    $title = str_replace(array('&Agrave;', '&agrave;', '&Aacute;', '&aacute;', '&Egrave;', '&egrave;', '&Eacute;', '&eacute;', '&Igrave;', '&igrave;', '&Iacute;', '&iacute;', '&Ntilde;', '&ntilde;', '&Ograve;', '&ograve;', '&Oacute;', '&oacute;', '&Ugrave;', '&ugrave;', '&Uacute;', '&uacute;', '&Uuml;', '&uuml;', '&Atilde;', '&sup3;', '&aelig;', '&thorn;', '&aacute;', '&eth;', '&uml;', '&ouml;', '&Ouml;'), array('A', 'a', 'A', 'a', 'E', 'e', 'E', 'e', 'I', 'i', 'I', 'i', 'N', 'n', 'O', 'o', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'o', '', 'ae', 'th', 'a', 'd', 'o', 'o', 'O'), $title);
    $title = str_replace("&amp;", "&", $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $title = str_replace(
            array(":", "?", ".", "!", "$", "^", "*", ",", ";", "'", '"', "%", "~", "@", "#", "[", "]", "<", ">", "\\", "/", "=", "+"), "", $title);
    $title = str_replace(array('_', " ", "&"), array("-", "-", "und"), $title);
    $title = htmlentities(strtolower($title));
    $title = str_replace(array('&auml;', '&ouml;', '&uuml;', '&szlig;'), array('ae', 'oe', 'ue', 'ss'), $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $results = rawurlencode($title);
    return "$results";
}

function seo_clean_titles_regular($title) {
    $title = str_replace(array('&Agrave;', '&agrave;', '&Aacute;', '&aacute;', '&yacute;', '&Yacute;', '&Egrave;', '&egrave;', '&Eacute;', '&eacute;', '&Igrave;', '&igrave;', '&Iacute;', '&iacute;', '&Ntilde;', '&ntilde;', '&Ograve;', '&ograve;', '&Oacute;', '&oacute;', '&Ugrave;', '&ugrave;', '&Uacute;', '&uacute;', '&Uuml;', '&uuml;', '&Atilde;', '&sup3;', '&aelig;', '&thorn;', '&aacute;', '&eth;', '&uml;', '&ouml;', '&Ouml;'), array('A', 'a', 'A', 'a', 'y', 'Y', 'E', 'e', 'E', 'e', 'I', 'i', 'I', 'i', 'N', 'n', 'O', 'o', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'o', '', 'ae', 'th', 'a', 'd', 'o', 'o', 'O'), $title);
    $title = str_replace("&amp;", "&", $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $title = str_replace(
            array(":", "?", ".", "!", "$", "^", "*", ",", ";", "'", '"', "%", "~", "@", "#", "[", "]", "<", ">", "\\", "/", "=", "+"), "", $title);
    $title = str_replace(array("&"), array("und"), $title);
    $title = htmlentities(strtolower($title));
    $title = str_replace(array('&auml;', '&ouml;', '&uuml;', '&szlig;'), array('ae', 'oe', 'ue', 'ss'), $title);
    $title = preg_replace("/&([a-z]+);/", "", $title);
    $results = rawurlencode($title);
    return "$results";
}

function insert_get_seotitle_from_cid($a) {
    global $config, $conn;
    $query = "select name from channels where CID='" . mysql_real_escape_string($a[cid]) . "'";
    $executequery = $conn->execute($query);
    return seo_clean_titles_no_trail($executequery->fields[name]);
}

function insert_get_featured_members($a) {
    global $config, $conn;
    $query = "select USERID,username from members where status='1' AND featured='1' order by rand() limit 8";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_search_phrases($var) {
    global $config, $conn;
    $query = "select * from search_phrases WHERE type='" . mysql_real_escape_string($var[type]) . "' order by searchcount desc limit $config[max_search_phrases]";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_rating_stars($a) {
    global $conn;
    global $config;
    $rating = $a[rating];
    $count = floor($rating / 2);
    $thecount = 0;

    for ($i = 0; $i < $count; $i++) {
        $returnthis.="<span class=\"full_star\"></span>";
        $thecount++;
    }

    $ratingcount = $rating / 2;
    $ratingcount = $ratingcount - $count;

    if (($ratingcount >= 0.5) && ($ratingcount < 1)) {
        $returnthis.="<span class=\"half_star\"></span>";
        $thecount++;
    } elseif (($ratingcount > 0) && ($ratingcount < 0.5)) {
        $returnthis.="<span class=\"no_star\"></span>";
        $thecount++;
    }

    for ($i = $thecount; $i < 5; $i++) {
        $returnthis.="<span class=\"no_star\"></span>";
    }

    if ($rating > 0) {
        echo $returnthis;
    } else {
        echo "<span class=\"no_star\"></span><span class=\"no_star\"></span><span class=\"no_star\"></span><span class=\"no_star\"></span><span class=\"no_star\"></span>";
    }
}

function does_profile_exist($a) {
    global $conn;
    global $config;
    $query = "SELECT USERID FROM members WHERE username='" . mysql_real_escape_string($a) . "'";
    $executequery = $conn->execute($query);
    if ($executequery->recordcount() > 0)
        return true;
    else
        return false;
}

function update_viewcount_profile($a) {
    global $conn;
    $query = "UPDATE members SET profileviews = profileviews + 1 WHERE USERID='" . mysql_real_escape_string($a) . "'";
    $executequery = $conn->execute($query);
}

function session_verification() {
    if ($_SESSION[USERID] != "") {
        if (is_numeric($_SESSION[USERID])) {
            return true;
        }
    }
    else
        return false;
}

function insert_get_member_friends_count($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM friends WHERE USERID='" . mysql_real_escape_string($var[USERID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_member_subscribers_count($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM members_subscribers WHERE subscriber='" . mysql_real_escape_string($var[USERID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_member_subscribedto_count($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM members_subscribers WHERE subscribee='" . mysql_real_escape_string($var[USERID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_member_subscriptions_count($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM members_subscribers WHERE subscribee='" . mysql_real_escape_string($var[USERID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_subscribed_status($var) {
    global $conn;
    $query = "SELECT * FROM members_subscribers WHERE subscriber='" . mysql_real_escape_string($var[USERID]) . "' AND subscribee='" . mysql_real_escape_string($_SESSION[USERID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->getrows();
    $resultscount = count($results);
    if ($resultscount >= 1)
        return "true";
    else
        return "false";
}

function insert_get_friends_status($var) {
    global $conn;
    $query = "SELECT FID FROM friends WHERE USERID='" . mysql_real_escape_string($var[USERID]) . "' AND FRIENDID='" . mysql_real_escape_string($_SESSION[USERID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->getrows();
    $resultscount = count($results);
    if ($resultscount >= 1)
        return "true";
    else
        return "false";
}

function insert_get_member_profilepicture($var) {
    global $conn;
    $query = "SELECT profilepicture FROM members WHERE USERID='" . mysql_real_escape_string($var[USERID]) . "' limit 1";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[profilepicture];
    if ($results == "")
        return "noprofilepicture.gif";
    else
        return $results;
}

function generateCode($length) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
    $code = "";
    $clen = strlen($chars) - 1;
    while (strlen($code) < $length) {
        $code .= $chars[mt_rand(0, $clen)];
    }
    return $code;
}

function mailme($sendto, $sendername, $from, $subject, $sendmailbody, $bcc = "") {
    global $SERVER_NAME;
    $subject = nl2br($subject);
    $sendmailbody = nl2br($sendmailbody);
    $sendto = $sendto;
    if ($bcc != "") {
        $headers = "Bcc: " . $bcc . "\n";
    }
    $headers .= "From: " . $from . "\n";
    $headers .= "Content-Type: text/html\n";
    mail("$sendto", "$subject", "$sendmailbody", "$headers");
}

function listdays($selected) {
    $days = "";
    for ($i = 1; $i <= 31; $i++) {
        $d = $i;
        if ($i < 10)
            $d = "0" . $i;

        if ($i == $selected) {
            $days .= "<option value=\"$d\" selected>$i</option>";
        } else {
            $days .= "<option value=\"$d\">$i</option>";
        }
    }
    return $days;
}

function listmonths($selected) {
    $months = "";
    $allmonths = array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    for ($i = 1; $i <= 12; $i++) {
        $m = $i;
        if ($i < 10)
            $m = "0" . $i;
        if ($i == $selected) {
            $months .= "<option value=\"$m\" selected>$allmonths[$i]</option>";
        } else {
            $months .= "<option value=\"$m\">$allmonths[$i]</option>";
        }
    }
    return $months;
}

function listyears($selected) {
    $years = "";
    $thisyear = date("Y");
    for ($i = $thisyear - 100 + 13; $i <= $thisyear; $i++) {

        if ($i == $selected)
            $years .= "<option value=\"$i\" selected>$i</option>";
        else
            $years .= "<option value=\"$i\">$i</option>";
    }
    return $years;
}

function listcountries($selected) {
    $country = "";
    $countries = array("Trinidad and Tobago", "Barbados", "Jamaica", "Grenada", "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antartica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Ascension Island", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Botswana", "Bouvet Island", "Brazil", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde Islands", "Cayman Islands", "Chad", "Chile", "China", "Christmas Island", "Colombia", "Comoros", "Cook Islands", "Costa Rica", "Cote d Ivoire", "Croatia/Hrvatska", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Ireland", "Isle of Man", "Israel", "Italy", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte Island", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn Island", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion Island", "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Lucia", "San Marino", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovak Republic", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia", "Spain", "Sri Lanka", "Suriname", "Svalbard", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tokelau", "Tonga Islands", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu", "Uganda", "Ukraine", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Western Sahara", "Western Samoa", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe");
    for ($i = 0; $i < count($countries); $i++) {
        if ($selected == $countries[$i]) {
            $country .="<option value=\"$countries[$i]\" selected>$countries[$i]</option>";
        } else {
            $country .="<option value=\"$countries[$i]\">$countries[$i]</option>";
        }
    }
    return $country;
}

function getPostData($up_dir, $tmp_sid) {
    $param_array = array();
    $buffer = "";
    $key = "";
    $value = "";
    $paramFileName = $up_dir . $tmp_sid . ".params";
    $fh = fopen($paramFileName, 'r') or kak("Error: Unable to open $paramFileName");

    while (!feof($fh)) {
        $buffer = fgets($fh, 4096);
        list($key, $value) = explode('=', trim($buffer));
        $value = str_replace("~EQLS~", "=", $value);
        $value = str_replace("~NWLN~", "\r\n", $value);

        if (isset($key) && isset($value) && strlen($key) > 0 && strlen($value) > 0) {
            if (preg_match('/(.*)\[(.*)\]/i', $key, $match)) {
                $param_array[$match[1]][$match[2]] = $value;
            } else {
                $param_array[$key] = $value;
            }
        }
    }

    fclose($fh);

    if (isset($param_array['delete_param_file']) && $param_array['delete_param_file'] == 1) {
        for ($i = 0; $i < 5; $i++) {
            if (unlink($paramFileName)) {
                break;
            } else {
                sleep(1);
            }
        }
    }

    return $param_array;
}

function generatevideothumbs($theconvertimg, $thevideoimgnew, $thewidth, $theheight) {
    global $config;
    $convertimg = $theconvertimg;
    $videoimgnew = $thevideoimgnew;

    $theimagesizedata = GetImageSize($convertimg);
    $videoimgwidth = $theimagesizedata[0];
    $videoimgheight = $theimagesizedata[1];
    $videoimgformat = $theimagesizedata[2];

    $whratio = 1;
    if ($videoimgwidth > $thewidth) {
        $whratio = $thewidth / $videoimgwidth;
    }

    if ($whratio != 1) {
        $dest_height = $whratio * $videoimgheight;
        $dest_width = $thewidth;
    } else {
        $dest_height = $videoimgheight;
        $dest_width = $videoimgwidth;
    }

    if ($dest_height > $theheight) {
        $whratio = $theheight / $dest_height;
        $dest_width = $whratio * $dest_width;
        $dest_height = $theheight;
    }

    if ($videoimgformat == 2) {
        $videoimgsource = @imagecreatefromjpeg($convertimg);
        $videoimgdest = @imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($videoimgdest, $videoimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $videoimgwidth, $videoimgheight);
        imagejpeg($videoimgdest, $videoimgnew, 100);
        imagedestroy($videoimgsource);
        imagedestroy($videoimgdest);
    } elseif ($videoimgformat == 3) {
        $videoimgsource = imagecreatefrompng($convertimg);
        $videoimgdest = imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($videoimgdest, $videoimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $videoimgwidth, $videoimgheight);
        imagepng($videoimgdest, $videoimgnew, 9);
        imagedestroy($videoimgsource);
        imagedestroy($videoimgdest);
    } else {
        $videoimgsource = imagecreatefromgif($convertimg);
        $videoimgdest = imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($videoimgdest, $videoimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $videoimgwidth, $videoimgheight);
        imagejpeg($videoimgdest, $videoimgnew, 100);
        imagedestroy($videoimgsource);
        imagedestroy($videoimgdest);
    }
}

function generatevideothumbs2($theconvertimg, $thevideoimgnew, $thewidth, $theheight) {
    global $config;
    $convertimg = $theconvertimg;
    $videoimgnew = $thevideoimgnew;

    $theimagesizedata = GetImageSize($convertimg);
    $videoimgwidth = $theimagesizedata[0];
    $videoimgheight = $theimagesizedata[1];
    $videoimgformat = $theimagesizedata[2];

    $dest_width = $thewidth;
    $dest_height = $theheight;

    if ($videoimgformat == 2) {
        $videoimgsource = @imagecreatefromjpeg($convertimg);
        $videoimgdest = @imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($videoimgdest, $videoimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $videoimgwidth, $videoimgheight);
        imagejpeg($videoimgdest, $videoimgnew, 100);
        imagedestroy($videoimgsource);
        imagedestroy($videoimgdest);
    } elseif ($videoimgformat == 3) {
        $videoimgsource = imagecreatefrompng($convertimg);
        $videoimgdest = imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($videoimgdest, $videoimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $videoimgwidth, $videoimgheight);
        imagepng($videoimgdest, $videoimgnew, 9);
        imagedestroy($videoimgsource);
        imagedestroy($videoimgdest);
    } else {
        $videoimgsource = imagecreatefromgif($convertimg);
        $videoimgdest = imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($videoimgdest, $videoimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $videoimgwidth, $videoimgheight);
        imagejpeg($videoimgdest, $videoimgnew, 100);
        imagedestroy($videoimgsource);
        imagedestroy($videoimgdest);
    }
}

function get_duration($mplayer, $vsource) {

    exec("$mplayer -vo null -ao null -frames 0 -identify $vsource", $p);
    while (list($k, $v) = each($p)) {
        if ($length = strstr($v, 'ID_LENGTH='))
            break;
    }
    $lx = explode("=", $length);
    $duration = $lx[1];
    return $duration;
}

function escape_data($data) {
    if (ini_get('magic_quotes_gpc')) {
        $data = stripslashes($data);
    }
    return $data;
}

function insert_get_stripped_phrase3($a) {
    $stripper = $a[details];
    $stripper = html_entity_decode($stripper);
    $stripper = preg_replace('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $stripper);
    $stripper = preg_replace('~&#0*([0-9]+);~e', 'chr(\\1)', $stripper);
    $stripper = escape_data($stripper);
    $pos = strpos($stripper, "object");
    $pos2 = strpos($stripper, "OBJECT");
    if ($pos === false) {
        $stripper2 = "<object>" . $stripper . "</object>";
        $stripper = $stripper2;
    } elseif ($pos2 === false) {
        $stripper2 = "<object>" . $stripper . "</object>";
        $stripper = $stripper2;
    }
    return $stripper;
}

function verify_valid_email($emailtocheck) {
    $eregicheck = "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.)+[a-zA-Z]{2,4}\$";
    return eregi($eregicheck, $emailtocheck);
}

function verify_email_unique($emailtocheck) {
    global $config, $conn;
    $query = "select count(*) as total from members where email='" . mysql_real_escape_string($emailtocheck) . "' limit 1";
    $executequery = $conn->execute($query);
    $totalemails = $executequery->fields[total];
    if ($totalemails >= 1) {
        return false;
    } else {
        return true;
    }
}

function insert_get_profile_subscribers($a) {
    global $config, $conn;
    $query = "select * from members_subscribers where subscriber=$a[userid] order by rand() limit 5";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_profile_subscribedto($a) {
    global $config, $conn;
    $query = "select * from members_subscribers where subscribee=$a[userid] order by rand() limit 5";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_profile_commentcount($a) {
    global $config, $conn;
    $query = "select count(*) as total from members_comments where PROFILEID=$a[userid]";
    $results = $conn->execute($query);
    $returnthis = $results->fields[total];
    return $returnthis;
}

function insert_get_profile_friends($a) {
    global $config, $conn;
    $query = "select * from friends where USERID=$a[userid] order by rand() limit 10";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_time_to_days_ago($a) {
    $currenttime = time();
    $timediff = $currenttime - $a[time];
    $oneday = 60 * 60 * 24;
    $dayspassed = floor($timediff / $oneday);
    if ($dayspassed == "0") {
        return "Today";
    } else {
        return $dayspassed . " days ago";
    }
}

function insert_get_stripped_phrase($a) {
    $stripper = $a[details];
    $stripper = str_replace("\\n", "<br>", $stripper);
    $stripper = str_replace("\\r", "", $stripper);
    $stripper = str_replace("\\", "", $stripper);
    return $stripper;
}

function insert_get_stripped_phrase2($a) {
    $stripper = $a[details];
    $stripper = str_replace("\\n", "\n", $stripper);
    $stripper = str_replace("\\r", "\r", $stripper);
    return $stripper;
}

function insert_get_userid_from_audioid($var) {
    global $conn;
    $query = "SELECT USERID FROM audios WHERE AUDIOID='" . mysql_real_escape_string($var[AUDIOID]) . "'";
    $executequery = $conn->execute($query);
    $getUSERID = $executequery->fields[USERID];
    return "$getUSERID";
}

function insert_get_channel_audio_details($var) {
    global $config, $conn;
    $query = "SELECT * FROM audios WHERE AUDIOID='" . mysql_real_escape_string($var[AUDIOID]) . "' limit 1";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_title_from_audioid($var) {
    global $conn;
    $query = "SELECT title FROM audios WHERE AUDIOID='" . mysql_real_escape_string($var[AUDIOID]) . "'";
    $executequery = $conn->execute($query);
    $gettitle = $executequery->fields[title];
    echo "$gettitle";
}

function insert_get_audio_categories_name($var) {
    global $conn;
    $query = "SELECT categories FROM audios WHERE AUDIOID='" . mysql_real_escape_string($var[AUDIOID]) . "'";
    $executequery = $conn->execute($query);
    $tempcategories = $executequery->fields[categories];

    $temp = explode("|", $tempcategories);
    for ($i = 1; $i < count($temp); $i++)
        $list.=" or CATID='" . $temp[$i] . "'";
    $query = "select name from categories_audios where CATID='$temp[0]' $list";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[name];
    echo "$results";
}

function insert_get_audio_categories_id($var) {
    global $conn;
    $query = "SELECT categories FROM audios WHERE AUDIOID='" . mysql_real_escape_string($var[AUDIOID]) . "'";
    $executequery = $conn->execute($query);
    $tempcategories = $executequery->fields[categories];

    $temp = explode("|", $tempcategories);
    for ($i = 1; $i < count($temp); $i++)
        $list.=" or CATID='" . $temp[$i] . "'";
    $query = "select catid from categories_audios where CATID='$temp[0]' $list";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[catid];
    echo "$results";
}

function insert_get_audio_categories_list($a) {
    global $conn;
    $query = "SELECT categories FROM audios WHERE AUDIOID='" . mysql_real_escape_string($a[audioid]) . "'";
    $executequery = $conn->execute($query);
    $a = $executequery->fields[categories];
    if ($a != "") {
        $temp = explode("|", $a);
        if (count($temp) >= 1)
            for ($i = 1; $i < count($temp); $i++)
                $list.=" or CATID=" . $temp[$i];
        $query = "select CATID,name from categories_audios where CATID=$temp[0] $list";
        $executequery2 = $conn->execute($query);
        $results = $executequery2->getrows();
        return $results;
    }
}

function insert_get_audio_added_date($a) {
    global $conn;
    $query = "SELECT date_added FROM audios WHERE AUDIOID='" . mysql_real_escape_string($a[audioid]) . "'";
    $executequery = $conn->execute($query);
    $list = explode('-', $executequery->fields[date_added]);
    print_r($list[2]);
    print_r('-');
    print_r($list[1]);
    print_r('-');
    print_r($list[0]);
}

function insert_get_audio_comment_added_time($a) {
    global $conn;
    $query = "SELECT time_added FROM audios_comments WHERE CID='$a[cid]'";
    $executequery = $conn->execute($query);
    $timeadded = $executequery->fields[time_added];
    echo date('Y-m-d', $timeadded);
}

function insert_get_seotitle_from_audioid($a) {
    global $config, $conn;
    $query = "select title from audios where AUDIOID='" . mysql_real_escape_string($a[audioid]) . "'";
    $executequery = $conn->execute($query);
    return seo_clean_titles($executequery->fields[title]);
}

function insert_get_audio_categories($a) {
    global $config, $conn;
    $query = "select * from categories_audios order by name asc";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_audio_categories_count($a) {
    global $conn;
    global $config;
    $query = "SELECT count(*) AS total FROM audios WHERE categories='" . mysql_real_escape_string($a[catid]) . "' AND active='1'";
    $results = $conn->execute($query);
    $returnthis = $results->fields[total];
    return $returnthis;
}

function does_audio_exist($a) {
    global $conn;
    global $config;
    $query = "SELECT title FROM audios WHERE AUDIOID='" . mysql_real_escape_string($a) . "'";
    $executequery = $conn->execute($query);
    if ($executequery->recordcount() > 0)
        return true;
    else
        return false;
}

function private_audio_access_check($saudioid, $suserid) {
    global $conn;
    global $config;
    $query = "SELECT USERID,public FROM audios WHERE AUDIOID='" . mysql_real_escape_string($saudioid) . "'";
    $executequery = $conn->execute($query);
    $vuserid = $executequery->fields['USERID'];
    $vpublic = $executequery->fields['public'];
    if ($vpublic == "0") {
        if ($suserid == $vuserid) {
            return true;
        } else {
            $query = "SELECT count(*) as total FROM friends WHERE USERID='" . mysql_real_escape_string($vuserid) . "' AND FRIENDID='" . mysql_real_escape_string($suserid) . "'";
            $executequery = $conn->execute($query);
            $totalcount = $executequery->fields[total];
            if ($totalcount > 0) {
                return true;
            } else {
                return false;
            }
        }
    } else {
        return true;
    }
}

function update_viewcount_audio($a) {
    global $conn, $qtest;
    $query = "UPDATE audios SET viewcount = viewcount + 1 WHERE AUDIOID='" . mysql_real_escape_string($a) . "'";
    $executequery = $conn->execute($query);
}

function update_last_viewed_audio($a) {
    global $conn;
    $query = "UPDATE audios SET last_viewed='" . date("Y-m-d H:i:s") . "' WHERE AUDIOID='" . mysql_real_escape_string($a) . "'";
    $executequery = $conn->execute($query);
}

function update_audios_you_viewed($a) {
    global $conn;
    $query = "UPDATE members SET audiosyouviewed = audiosyouviewed + 1 WHERE USERID='" . mysql_real_escape_string($a) . "'";
    $executequery = $conn->execute($query);
}

function update_your_audios_viewed($a) {
    global $conn;
    $query = "UPDATE members SET youraudiosviewed  = youraudiosviewed  + 1 WHERE USERID='" . mysql_real_escape_string($a) . "'";
    $executequery = $conn->execute($query);
}

## funciton to insert the audio being viewed...

function insert_audios_viewed($var) {
    global $conn;
    if ($var != "" && $var != "0") {
        $query = "insert into audios_viewed values($var,now())";
        $executequery = $conn->execute($query);
    }
}

function insert_get_member_audios_count($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM audios WHERE USERID='" . mysql_real_escape_string($var[USERID]) . "' AND public='1' AND active='1'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_channel_audios_count($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM channels_audios WHERE CID='" . mysql_real_escape_string($var[CID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_audio_favorited_count($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM audios_favorited WHERE AUDIOID='" . mysql_real_escape_string($var[AUDIOID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_fav_audio_status($var) {
    global $conn;
    $query = "SELECT * FROM audios_favorited WHERE USERID='" . mysql_real_escape_string($_SESSION[USERID]) . "' AND AUDIOID=$var[AUDIOID]";
    $executequery = $conn->execute($query);
    $results = $executequery->getrows();
    $resultscount = count($results);
    if ($resultscount >= 1)
        return "true";
    else
        return "false";
}

function insert_get_tags_audio($a) {
    global $conn;
    $query = "SELECT tags FROM audios WHERE AUDIOID='" . mysql_real_escape_string($a[audioid]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[tags];
    $returnthis = explode(" ", $results);
    return $returnthis;
}

function ajax_rate_audio($audioidx, $userrating) {
    global $config, $conn;
    $query = "SELECT ratingcount, rating, voter_id FROM audios WHERE AUDIOID='" . mysql_real_escape_string($audioidx) . "'";
    $executequery = $conn->execute($query);
    $voter_id = $executequery->fields[voter_id];
    $ratingcounttemp = $executequery->fields[ratingcount];
    $ratingtemp = $executequery->fields[rating];

    $alreadyvoted = false;
    $query2 = "SELECT value FROM config WHERE setting='only_vote_once'";
    $executequery2 = $conn->execute($query2);
    $only_vote_once = $executequery2->fields[value];
    if ($only_vote_once == "1") {
        $thisvoter = "|";
        $thisvoter .= $_SESSION[USERID];
        $thisvoter .= "|";
        $alreadyvoted = strstr($voter_id, $thisvoter);
    }

    if (!$alreadyvoted) {
        if ($voter_id == "") {
            $voter_id .= "|";
        }
        $voter_id .= $_SESSION[USERID];
        $voter_id .= "|";
        $totaltemp = $ratingcounttemp * $ratingtemp;
        $newratingcount = $ratingcounttemp + 1;
        $newrating = ($totaltemp + $userrating) / $newratingcount;

        $query3 = "UPDATE audios SET ratingcount=ratingcount+1, rating=$newrating, voter_id='$voter_id' WHERE AUDIOID='" . mysql_real_escape_string($audioidx) . "'";
        $conn->execute($query3);
        return true;
    } else {
        return false;
    }
}

function insert_get_profile_audios($a) {
    global $config, $conn;
    $query = "select * from audios where USERID=$a[userid] AND public='1' AND active='1' order by AUDIOID desc limit 8";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_profile_favoriteaudios($a) {
    global $config, $conn;
    $query = "select AUDIOID from audios_favorited where USERID=$a[userid] order by FID desc limit 5";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

function insert_get_member_favorited_count_audios($var) {
    global $conn;
    $query = "SELECT count(*) as total FROM audios_favorited WHERE USERID='" . mysql_real_escape_string($var[USERID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[total];
    echo "$results";
}

function insert_get_eaudiourl($a) {
    global $config, $conn;
    $query = "select title from audios where AUDIOID='" . mysql_real_escape_string($a[audioid]) . "'";
    $executequery = $conn->execute($query);
    $turl = $config['baseurl'] . "/audios/" . $a[audioid] . "/" . $executequery->fields[title];
    return $config['baseurl'] . "/login.php?redirect=" . base64_encode($turl);
}

function insert_get_static($var) {
    global $conn;
    $query = "SELECT $var[sel] FROM static WHERE ID='" . mysql_real_escape_string($var[ID]) . "'";
    $executequery = $conn->execute($query);
    $returnme = $executequery->fields[$var[sel]];
    $returnme = strip_mq_gpc($returnme);
    echo "$returnme";
}

function verify_email_username($usernametocheck) {
    global $config, $conn;
    $query = "select count(*) as total from members where username='" . mysql_real_escape_string($usernametocheck) . "' limit 1";
    $executequery = $conn->execute($query);
    $totalu = $executequery->fields[total];
    if ($totalu >= 1) {
        return false;
    } else {
        return true;
    }
}

function insert_get_acatname($var) {
    global $conn;
    $query = "SELECT name FROM categories_audios WHERE CATID='" . mysql_real_escape_string($var[CID]) . "'";
    $executequery = $conn->execute($query);
    $results = $executequery->fields[name];
    return "$results";
}

function insert_get_audios_from_catid($a) {
    global $config, $conn;
    $query = "SELECT AUDIOID,title,ext from audios where categories='" . mysql_real_escape_string($a[CID]) . "' order by rand() limit " . mysql_real_escape_string($a[lim]) . "";
    $results = $conn->execute($query);
    $returnthis = $results->getrows();
    return $returnthis;
}

## function called prior to create xml files for playlists...

function create_playlist_xml($playlistids,$fromAdmin = 0) {
    if (is_array($playlistids)) {
        foreach ($playlistids as $key => $val) {
            create_playlist_xml_file($val,$fromAdmin);
        }
    } else {
        create_playlist_xml_file($playlistids);
    }
}

## function to create xml files for the playlist...

function create_playlist_xml_file($playlistid, $fromAdmin = 0) {
    global $config, $conn;

    $query = "select a.title,a.AUDIOID,a.artist,m.username,a.audio_name,a.ext,a.date_added,c.name as cat_name from playlist_audios pa left join audios a on (pa.AUDIOID=a.AUDIOID) left join members m on (a.USERID=m.USERID) left join categories_audios c on (a.categories=c.CATID) where pa.PLAYLISTID = '$playlistid'";
    $results = $conn->execute($query);
    $data = $results->getrows();
    $myFile = "playlists/" . $playlistid . ".xml";
    if ($fromAdmin == "1")
        $myFile = "../playlists/" . $playlistid . ".xml";
    
    $fh = fopen($myFile, 'w') or die("can't open file " . $myFile);

    $stringData = "";
    $stringData = "<?xml version='1.0' encoding='UTF-8'?>
					<playlist version='1' xmlns='http://xspf.org/ns/0/'>
				<trackList>";
    foreach ($data as $key => $val) {
        $audioYear = date("Y", strtotime($val["date_added"]));
        $stringData .="<track>";
        $stringData .="	<creator>" . $val["username"] . "</creator>";
        $stringData .="<title>" . $val["title"] . "</title>";
        $stringData .="<location>" . $config[baseurl] . "/adata/" .$val["cat_name"]."/". $audioYear . "/" . $val["audio_name"] . "</location>";
        $image = $config[baseurl] . "/images/audiothumbs/default.png";
        if (file_exists("images/audiothumbs/" . $val["AUDIOID"] . "-1" . $val["ext"]))
            $image = $config[baseurl] . "/images/audiothumbs/" . $val["AUDIOID"] . "-1" . $val["ext"];
        $stringData .="<image>" . $image . "</image>";
        $stringData .="</track>";
    }
    $stringData .="</tracklist>";
    $stringData .="</playlist>";
    fwrite($fh, $stringData);
    fclose($fh);
}

## funciton to remove playlist xml files...

function remove_playlist_xml($playlistId) {
    $file_path = "playlists/" . $playlistId . ".xml";

    if (file_exists($file_path)) {
        unlink($file_path);
    }
}

## function to get the list of the playlists created by the users...

function getPlaylists($userId = "") {
    $query = "";
    global $config, $conn;
    $query = "SELECT * FROM `playlists` WHERE `active` =1";
    if ($userId != "" && is_numeric($userId))
        $query .=" and USERID='" . (int) $userId . "'";

    $results = $conn->execute($query);
    $data = $results->getrows();
    return $data;
}

## funciton to insert multiple songs to multiple playlists...
/*
  The format should be as follows...
  [PlaylistID]=>array(sondID1,songID2,...)
 */

function AddAudiosToPlaylist($params) {
    $insertStr = "";
    global $conn;
    if (!empty($params)) {
        foreach ($params as $playlist => $audioList) {
            foreach ($audioList as $val) {
                $insertStr .="(" . $playlist . "," . $val . "," . $_SESSION[USERID] . ",'" . date("Y-m-d") . "'),";
            }
        }
        $insertStr = substr($insertStr, 0, -1);
        if ($insertStr != "") {
            $query = "insert into playlist_audios values " . $insertStr;
            $conn->execute($query);
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

## function to get the category name from category id
function fetch_category_name_from_id($catID){
    if(is_numeric($catID) && $catID>0){
        global $conn;
        $catName="";
        $query="select name from categories_audios where CATID='".$catID."'";
        $execute=$conn->execute($query);
        $catName = $execute->fields[name];
        return $catName;
    }
}

?>